<?php

namespace app\api\controller\v21;

use app\api\controller\v2\Auth;
use app\common\cachemodel\Fortune;
use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\OrdersGoods;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\OrdersLib as OrdersCacheModelLib;
use app\common\cachemodel\RectificationEvent;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZlcrCustomReportQuestion;
use app\common\cachemodel\ZlTarotRecords;
use app\common\lib\exception\ApiException;
use app\common\lib\PushQueue;
use app\common\lib\Util;
use Exception;
use think\Db;
use think\Env;
use think\Log;
use think\response\Json;

/**
 * @version 2.5.0 订单控制器
 * Class Orders
 * @package app\api\controller\v13
 */
class Orders extends Auth
{
    protected $completeAnswerTime;//接单后回答完成时长
    public $msg;

    public function _initialize()
    {
        parent::_initialize();
        $this->completeAnswerTime = Env::get('queue.custom_report_answer6_delay');
    }

    /**
     * 接口，订单列表
     * @return Json
     * @throws Exception
     */
    public function index()
    {
        $this->msg = '';
        OrdersCacheModelLib::getUserAllUnpaidOrder($this->user['id']);
        $type = input('param.type/d', 0);
        $order_type = input('param.order_type/s', '');
        $version_code = input('param.version_code/d', 0);
        $is_live = input('is_live/d', 0);
        $ordersModel = new OrdersCacheModel();
        //1.9.6版本以后不需要过滤本命预测
        if ($version_code)
        {
            switch (true)
            {
                case $this->headers['app-type'] === 'ios' && $version_code >= 57:
                case $this->headers['app-type'] === 'android' && $version_code >= 79:
                    $orderTypeArr = explode(',', $order_type);
                    if (in_array(23, $orderTypeArr, false))
                    {
                        $orderTypeArr = array_merge($orderTypeArr, [23, 24, 25, 26]);
                        $order_type = implode(',', $orderTypeArr);
                    }
                    $orders = $ordersModel->getUserAllOrder($this->user['id'], $type, $order_type, '', true, $is_live);
                    break;
                case $this->headers['app-type'] === 'ios' && $version_code >= 22:
                case $this->headers['app-type'] === 'android' && $version_code >= 34:
                    $orders = $ordersModel->getUserAllOrder($this->user['id'], $type, $order_type, '', true, $is_live);
                    break;
                default:
                    $orders = $ordersModel->getUserAllOrder($this->user['id'], $type, $order_type, '7', true, $is_live);
                    break;
            }
        } else
        {
            $orders = $ordersModel->getUserAllOrder($this->user['id'], $type, $order_type, '7', true, $is_live);
        }
        if ($orders)
        {
            try
            {
                $orders['data'] = array_values($this->resetOrderList($orders['ids'], $orders['data']));
                unset($orders['ids']);
            }
            catch (Exception $e)
            {
                Log::write('订单列表数据问题：' . $e->getMessage() . '错误文件和行数：' . $e->getFile() . ':' . $e->getLine(), 'error', true);

                return show(config('code.error'), '服务异常，请稍后重试');
            }
        }

        $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);

        $orders['coin_num'] = (int)($user_coin['balance'] ?? 0);
        $orders['pwd_status'] = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;

        return show(config('code.success'), '加载成功', $orders);
    }

    /**
     * 订单列表数据重构
     * @param $order_ids
     * @param $orders
     * @return array
     * @throws Exception
     */
    public function resetOrderList($order_ids, $orders)
    {
        $data = [];
        $ordersModel = new OrdersCacheModel();
        foreach ($order_ids as $order_id)
        {
            $orders[$order_id] = $ordersModel->ordersDetail2($orders[$order_id]);
            $data[$order_id]['order_type'] = $orders[$order_id]['order_type'];
            $data[$order_id]['order_id'] = $orders[$order_id]['order_id'];
            $data[$order_id]['trade_type'] = $orders[$order_id]['trade_type'];
            $data[$order_id]['total_amount'] = $orders[$order_id]['total_amount'];
            $data[$order_id]['create_time'] = date('Y-m-d H:i:s', $orders[$order_id]['create_time']);
            $data[$order_id]['order_btns'] = $ordersModel->getIndexOrderBtn($orders[$order_id]);
            $data[$order_id]['order_status'] = $orders[$order_id]['status_des'];
            $data[$order_id]['mini_type_des'] = $orders[$order_id]['mini_type_des'];
            $data[$order_id]['is_live'] = (int)$orders[$order_id]['env_type'] == 8 ? 1 : 0;
            $order_data['des1'] = NULL;//订单描述1初始化
            $order_data['des2'] = NULL;//订单描述2初始化
            $order_data['img'] = NULL;//订单图片初始化
            $data[$order_id]['order_name'] = '';//订单一级标题
            $order_data['title'] = '';//订单二级标题
            switch ($orders[$order_id]['order_type'])
            {
                //重组校准生辰订单
                case 1:
                    $rec = $ordersModel->RecRead($orders[$order_id]);
                    $data[$order_id]['order_name'] = '校准生辰';
                    $order_data['title'] = '校准生辰服务';
                    $order_data['des1'] = '出生时间：' . date('Y-m-d', $rec['data']['start_time']);
                    $order_data['des2'] = '时间范围：' . date('H:i', $rec['data']['start_time']) . '-' . ((date('d', $rec['data']['start_time']) != date('d', $rec['data']['end_time'])) ? '次日' : '') . date('H:i', $rec['data']['end_time']);
                    break;
                //重组运势订单
                case 2:
                case 3:
                case 4:
                case 12:
                    $fortune = $ordersModel->FortuneRead($orders[$order_id]);
                    switch ($orders[$order_id]['order_type'])
                    {
                        case 2:
                            $order_data['title'] = '每日运势';
                            break;
                        case 3:
                            $order_data['title'] = '月度运势';
                            break;
                        case 4:
                            $order_data['title'] = '年度运势';
                            break;
                        default :
                            $order_data['title'] = '运势';
                            break;
                    }
                    $data[$order_id]['order_name'] = '运势订单';
                    $recode_name = [];
                    foreach ($fortune['recode_data'] as $recode)
                    {
                        $recode_name[] = $recode['name'];
                        $order_data['des2'] = '开通日期：' . $fortune['fortune_data']['start_time'] . '至' . $fortune['fortune_data']['end_time'];
                    }
                    $frame = $recode_name ? implode(',', $recode_name) : '';
                    $order_data['des1'] = '开通档案：' . $frame;
                    foreach ($fortune['recode_data'] as $recodeItem)
                    {
                        if (!$recodeItem['status'])
                        {
                            $data[$order_id]['order_btns'] = Util::orderBtnReset($data[$order_id]['order_btns']);
                            continue;
                        }
                    }
                    break;
                case 5: //重组地图订单
                    $map = $ordersModel->MapRead($orders[$order_id]);
                    $data[$order_id]['order_name'] = '幸运之城';
                    $order_data['title'] = '幸运之城解锁';
                    $map_recode = $map['recode_data'] ? current($map['recode_data']) : [];
                    $game = [];
                    foreach ($map['goods_data'] as $acg)
                    {
                        $game[] = $acg['name'];
                    }
                    $map_count = count($game);
                    $gabe_sta = $game ? implode(',', $game) : '';
                    $gids = array_keys($map['goods_data']);
                    if ($map_count > 2)
                    {
                        $des = '开通' . implode(',', array_slice($game, 0, 2)) . '等' . $map_count . '条';
                    } elseif (in_array(18, $gids, false))
                    {
                        $des = '开通命运之城';

                    } elseif (in_array(19, $gids, false))
                    {
                        $des = '开通全内容打包解锁';
                    } else
                    {
                        $des = '开通' . $gabe_sta . '等' . $map_count . '条';
                    }
                    $order_data['des1'] = '购买档案：' . ($map_recode['name'] ?? '');
                    $order_data['des2'] = '订单详情：' . $des;
                    $data[$order_id]['order_data'][] = [
                        'name' => '订单详情',
                        'value' => $gabe_sta,
                    ];
                    break;
                case 7: //重组本命预测订单
                    $report = $ordersModel->MapRead($orders[$order_id]);
                    $data[$order_id]['order_name'] = '一生报告订单';
                    $order_data['title'] = '一生报告解锁';
                    $report_recode = $report['recode_data'] ? current($report['recode_data']) : [];
                    $game = [];
                    foreach ($report['goods_data'] as $acg)
                    {
                        $game[] = $acg['name'];
                    }
                    $map_count = count($game);
                    $gabe_sta = $game ? implode(',', $game) : '';
                    if ($map_count > 1)
                    {
                        $des = '开通' . implode(',', array_slice($game, 0, 1)) . '等' . $map_count . '篇';
                    } else
                    {
                        $des = '开通' . $gabe_sta;
                    }
                    $order_data['des1'] = '购买档案：' . $report_recode['name'] ?? '';
                    $order_data['des2'] = $des;
                    $data[$order_id]['order_data'][] = [
                        'name' => '订单详情',
                        'value' => $gabe_sta,
                    ];
                    foreach ($report['recode_data'] as $recodeItem)
                    {
                        if (isset($recodeItem['status']) && !$recodeItem['status'])
                        {
                            $data[$order_id]['order_btns'] = Util::orderBtnReset($data[$order_id]['order_btns']);
                            continue;
                        }
                    }
                    break;
                case 6://重组视频订单
                    $video = $ordersModel->VideoRead($orders[$order_id]);
                    $video_goods = $video['goods_data'] ? current($video['goods_data']) : [];
                    $data[$order_id]['order_name'] = '教学视频';
                    $data[$order_id]['video_id'] = $video['video_id'];
                    $order_data['title'] = $video_goods['name'];
                    $order_data['des1'] = $video['goods_data_des'];
                    break;
                case 8: //重组vip订单
                    $vip = $ordersModel->VipRead($orders[$order_id]);
                    $vip_goods = $vip['goods_data'] ? current($vip['goods_data']) : [];
                    $data[$order_id]['order_name'] = '开通会员';
                    $order_data['title'] = '会员开通';
                    $order_data['des1'] = '开通时长：' . $vip_goods['name'];
                    //若会员购买成功后，显示有效期
                    if ((int)$orders[$order_id]['status'] === 4)
                    {
                        $order_data['des2'] = '有效期至：' . $vip['vip_end_time'];
                    }
                    break;
                case 14: // 商城订单
                    $mall = $ordersModel->MallRead($orders[$order_id]);
                    $data[$order_id]['order_name'] = '商城订单';
                    $order_data['title'] = $mall['goods_data']['name'] ?? '';
                    $order_data['des1'] = $mall['goods_data_des'] ?? '';
                    $img = $mall['goods_data']['imgs'] ? explode(',', $mall['goods_data']['imgs'])[0] : '';
                    $order_data['img'] = $img;
                    $data[$order_id]['gid'] = isset($mall['goods_data']['id']) ? (int)$mall['goods_data']['id'] : 0;
                    $data[$order_id]['sid'] = isset($mall['spec_info']['id']) ? (int)$mall['spec_info']['id'] : 0;
                    break;
                case 15://定制报告
                    $customReport = $ordersModel->CustomReport($orders[$order_id]);
                    $data[$order_id]['order_name'] = '定制报告订单';
                    $order_data['title'] = '定制报告';
                    $order_data['des1'] = '购买档案：' . implode('&', array_column($customReport['recode_data'], 'name'));
                    $data[$order_id]['gid'] = (int)$customReport['question_data']['gid'];
                    foreach ($customReport['recode_data'] as $recodeItem)
                    {
                        if (!$recodeItem['status'])
                        {
                            $data[$order_id]['order_btns'] = Util::orderBtnReset($data[$order_id]['order_btns']);
                            continue;
                        }
                    }
                    break;
                case 16://塔罗
                    $extend = json_decode($orders[$order_id]['extend'], true);
                    $data[$order_id]['order_name'] = '塔罗占卜订单';
                    $order_data['title'] = '塔罗占卜';
                    $order_data['des1'] = $extend['history']['content'];
                    $data[$order_id]['gid'] = (int)$orders[$order_id]['gid'];
                    break;
                case 17://合盘报告
                    $synastryReport = $ordersModel->SynastryReport($orders[$order_id]);
                    $rname = array_column($synastryReport['recode_data'], 'name');
                    $goods = current($synastryReport['goods_data']);
                    $data[$order_id]['order_name'] = '恋爱合盘报告订单';
                    $extend = json_decode($orders[$order_id]['extend'], true);
                    $data[$order_id]['srid'] = $extend['synastry_report']['srid'] ?? 1;
                    $order_data['title'] = config('synastryreport')[$data[$order_id]['srid']]['good_name'] ?? $goods['name'];
                    $order_data['des1'] = '开通档案：' . implode('&', $rname);
                    $order_data['des2'] = '当前关系：' . $synastryReport['relation_data']['name'];
                    $data[$order_id]['gid'] = (int)$orders[$order_id]['gid'];
                    foreach ($synastryReport['recode_data'] as $recodeItem)
                    {
                        if (!$recodeItem['status'])
                        {
                            $data[$order_id]['order_btns'] = Util::orderBtnReset($data[$order_id]['order_btns']);
                            continue;
                        }
                    }
                    break;
                case 18: // 心理测试订单
                    $mental_test = $ordersModel->MentalTestDetail($orders[$order_id]);
                    $data[$order_id]['order_name'] = '心理测试订单';
                    $order_data['title'] = $mental_test['name'];
                    $order_data['des1'] = $mental_test['short_describe'] ?? '';
                    $order_data['img'] = $mental_test['intro_picture'] ?? '';
                    break;
                case 19://直播看盘解答
                case 20://直播看盘解答
                case 21://直播看盘解答
                    $ordersModel->getAnswerInfo($orders[$order_id]);
                    $data[$order_id]['order_name'] = '主播订单';
                    $order_data['title'] = $orders[$order_id]['title'];
                    $order_data['des1'] = "直播间：{$orders[$order_id]['live_anchor']['name']}";
                    $order_data['des2'] = $orders[$order_id]['des2'] ?? '';
                    break;
                case 22://问答
                    $ordersModel->getQuestionInfo($orders[$order_id]);
                    $data[$order_id]['order_name'] = '问答订单';
                    $order_data['title'] = $orders[$order_id]['title'];
                    $order_data['des1'] = $orders[$order_id]['des2'];
                    break;
                case 23:
                    $ordersModel->getRelationFitInfo($orders[$order_id]);
                    $data[$order_id]['order_name'] = '关系研究所/爱情';
                    $order_data['title'] = '适合你的TA';
                    $order_data['des1'] = '购买档案：' . $orders[$order_id]['recode_data']['des'];
                    $order_data['des2'] = '开通：' . implode(',', array_column($orders[$order_id]['goods_data'], 'des'));
                    break;
                case 24:
                    $ordersModel->getRelationIdeaInfo($orders[$order_id]);
                    $data[$order_id]['order_name'] = '关系研究所/爱情';
                    $order_data['title'] = '你的理想型';
                    $order_data['des1'] = '单次解锁方案';
                    break;
                case 25:
                    $ordersModel->getRelationFollowInfo($orders[$order_id]);
                    $data[$order_id]['order_name'] = '关系研究所/爱情';
                    $order_data['title'] = '怎么追求TA';
                    $order_data['des1'] = '购买档案：' . $orders[$order_id]['recode'][0]['name'] . '&' . $orders[$order_id]['recode'][1]['name'];
                    break;
                case 26://关系研究所
                    $ordersModel->getRelationFollowInfo($orders[$order_id]);
                    $data[$order_id]['order_name'] = '关系研究所/爱情';
                    $order_data['title'] = '鉴"渣"神器';
                    $order_data['des1'] = '购买档案：' . $orders[$order_id]['recode_data']['des'];
                    break;
                case 27://年运拓展
                    $ordersModel->getYearLife($orders[$order_id]);
                    $order_data['des1'] = '开通档案：' . $orders[$order_id]['recode_data']['des'];
                    if ((int)$orders[$order_id]['gid'] === 91)
                    {
                        $data[$order_id]['order_name'] = '运势订单';
                        $order_data['title'] = '人生阶段';
                        $order_data['des2'] = '开通内容：' . $orders[$order_id]['des2'];
                    } elseif ((int)$orders[$order_id]['gid'] === 92)
                    {
                        $data[$order_id]['order_name'] = '运势订单';
                        $order_data['title'] = '年运筛查';
                    } else
                    {
                        $data[$order_id]['order_name'] = '运势订单';
                        $order_data['title'] = '未知';
                    }
                    break;
                case 28://八字
                    $ordersModel->getBazi($orders[$order_id]);
                    $order_data['des1'] = '开通档案：' . $orders[$order_id]['recode_data']['des'];
                    $isHuawei = Util::IsHuawei();
                    if ($isHuawei)
                    {
                        $data[$order_id]['order_name'] = '国学';
                    } else
                    {
                        $data[$order_id]['order_name'] = '八字';
                    }
                    if (\app\common\cachemodel\Goods::isBaziJsjr(28, $orders[$order_id]['gid']))
                    {
                        $order_data['title'] = '吉时吉日';
                        $order_data['des2'] = '开通日期：' . $orders[$order_id]['des2'];
                    } else if ((int)$orders[$order_id]['gid'] === 106)
                    {
                        $order_data['title'] = $isHuawei ? '取用详解' : '用神详解';
                    } elseif ((int)$orders[$order_id]['gid'] === 107)
                    {
                        $order_data['title'] = $isHuawei ? '格局解读' : '72格局判定';
                    }
                    break;
                case 29://冥想
                    $data[$order_id]['order_name'] = '冥想疗愈';
                    $ordersModel->getMeditation($orders[$order_id]);
                    $order_data['title'] = $orders[$order_id]['title'];
                    $order_data['des1'] = $orders[$order_id]['des1'];
                    $order_data['img'] = current($orders[$order_id]['goods_data'])['img'];
                    $order_data['gid'] = $orders[$order_id]['gid'];
                    break;
                case 30:
                case 31:
                    $data[$order_id]['order_name'] = 'AI';
                    $ordersModel->getAiAnswer($orders[$order_id]);
                    $order_data['title'] = $orders[$order_id]['title'];
                    $order_data['des1'] = $orders[$order_id]['des1'];
                    $order_data['img'] = current($orders[$order_id]['goods_data'])['img'];
                    $order_data['gid'] = $orders[$order_id]['gid'];
                    break;
                case 32:
                    $data[$order_id]['order_name'] = '后天星座';
                    $ordersModel->getAcquiredAstro($orders[$order_id]);
                    $order_data['title'] = $orders[$order_id]['title'];
                    $order_data['des1'] = $orders[$order_id]['des1'];
                    $order_data['img'] = current($orders[$order_id]['goods_data'])['img'];
                    $order_data['gid'] = $orders[$order_id]['gid'];
                    break;
                case 34://疗愈室充电时长
                    $data[$order_id]['order_name'] = 'AI';
                    $ordersModel->getAiVoice($orders[$order_id]);
                    $order_data['title'] = $orders[$order_id]['title'];
                    $order_data['des1'] = $orders[$order_id]['des1'];
                    $order_data['img'] = current($orders[$order_id]['goods_data'])['img'];
                    $order_data['gid'] = $orders[$order_id]['gid'];
                    break;
                case 35:
                    $data[$order_id]['order_name'] = '八字起名';
                    $ordersModel->getNameAnalyzeRecord($orders[$order_id]);
                    $order_data['title'] = $orders[$order_id]['title'];
                    $order_data['des1'] = $orders[$order_id]['des1'];
                    $order_data['des2'] = $orders[$order_id]['des2'];
                    $order_data['img'] = current($orders[$order_id]['goods_data'])['img'];
                    $order_data['gid'] = $orders[$order_id]['gid'];
                    break;
            }
            if (isset($order_data) && $order_data)
            {
                $order_data['gid'] = $orders[$order_id]['gid'];
                $data[$order_id]['data'][] = $order_data;
            }
        }

        return $data;
    }

    /**
     * 接口，获取订单详情
     * @throws Exception
     */
    public function read()
    {
        $this->msg = '';
        $order_id = input('param.order_id', '');
        if (!$order_id)
        {
            return show(config('code.error'), '未知的订单');
        }
        $ordersCacheModel = new OrdersCacheModel();
        $orders = current($ordersCacheModel->batchGetInfo([$order_id]));
        if ($orders)
        {
            if ($orders['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '订单不存在');
            }
            try
            {
                $info = $this->read_data_format($orders);
            }
            catch (\Exception $e)
            {
                Log::write('订单详情异常：' . $e->getMessage() . '错误文件和行数：' . $e->getFile() . ':' . $e->getLine(), 'error', true);

                return show(config('code.error'), '服务异常，请稍后重试');
            }

            return show(config('code.success'), '获取成功', $info);
        }

        return show(config('code.error'), '订单不存在');
    }

    /**
     * 组合订单详情数据格式
     * @param $orders
     * @return array
     * @throws Exception
     */
    private function read_data_format($orders)
    {
        $ordersModel = new OrdersCacheModel();
        $orders_details = $ordersModel->ordersDetail($orders);
        //订单数据重组
        $info = [
            'status_des' => $orders_details['mini_type_des'] ? $orders_details['status_des'] . $orders_details['mini_type_des'] : $orders_details['status_des'],
            'order_icon' => $this->getReadOrderBtn($orders_details)['icon'],
            'total_amount' => $orders_details['total_amount'],
            'trade_type' => (int)$orders_details['trade_type'],
            'order_id' => $orders_details['order_id'],
            'order_btn' => $this->getReadOrderBtn($orders_details)['btn'],
            'is_display_recommend_data' => $orders_details['is_display_recommend_data'],
            'des' => $orders_details['des'],
            'time_remaining' => $orders_details['time_remaining'],
            'coupon_data' => $orders_details['coupon_data'],
            'active_data' => $orders_details['active_data'],
            'coin_num' => OrdersCacheModelLib::getCoinNum($this->user['id']),
            'goods_data' => [],
            'recode_data' => NULL,
            'rectification_data' => NULL,
            'refund_data' => $orders_details['refund_data'],
            'note_tips' => '',
            'gid' => (int)($orders_details['gid'] ?? 0),
        ];

        // 待支付返回准币数量及是否设置准币支付密码
        if ($orders_details['status'] == 0)
        {
            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);
            $info['coin_num'] = (int)($user_coin['balance'] ?? 0);
            $info['pwd_status'] = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;
        }

        $info['order_data'][] = [
            'name' => '下单时间',
            'value' => date('Y-m-d H:i:s', $orders_details['create_time']),
        ];
        // 苹果支付不显示支付方式
        if ((int)$orders_details['trade_type'] !== 9)
        {
            $info['order_data'][] = [
                'name' => '支付方式',
                'value' => $orders_details['trade_type_des'],
            ];
        }
        if ($orders_details['pay_time'])
        {
            $info['order_data'][] = [
                'name' => '支付时间',
                'value' => date('Y-m-d H:i:s', $orders_details['pay_time']),
            ];
        }

        //重组购买的商品信息
        switch (true)
        {
            case (int)$orders_details['order_type'] === 1://生时矫正
                $detail = $ordersModel->RecRead($orders_details);
                //获取商品信息
                $info['goods_data']['price'] = current($detail['goods_data'])['now_prize'];
                $info['goods_data']['name'] = '校准生辰服务';
                $info['goods_data']['des'] = '';
                //获取档案信息
                $recode = current($detail['recode_data']);
                $info['recode_data']['des'] = $recode['name'];
                $info['recode_data']['rids'] = $recode['id'];
                //获取校正事件信息
                $info['rectification_data']['des1'] = date('Y-m-d', $detail['data']['start_time']);
                $info['rectification_data']['des2'] = date('H:i', $detail['data']['start_time']) . '至' . ((date('d', $detail['data']['start_time']) != date('d', $detail['data']['end_time'])) ? '次日' : '') . date('H:i', $detail['data']['end_time']);
                //获取校准生辰事件信息
                $events = (new RectificationEvent())->batchGetInfoByIds($orders_details['reid'], [
                    'id',
                    'status',
                    'reid',
                    'time',
                    'type',
                    'desc',
                ]);
                foreach ($events as $k => $event)
                {
                    unset($event['status'], $event['reid']);
                    $event['time'] = $event['time'] ? date('Y-m', $event['time']) : '';
                    $events[$k] = $event;
                }
                $info['rectification_data']['event'] = $events;
                break;
            case (int)$orders_details['order_type'] === 2://日运
            case (int)$orders_details['order_type'] === 3://月运
            case (int)$orders_details['order_type'] === 4://年运
                $detail = $ordersModel->FortuneRead($orders_details);
                if ($orders_details['order_type'] == 2)
                {
                    $info['goods_data']['name'] = '每日运势开通';
                } else if ($orders_details['order_type'] == 3)
                {
                    $info['goods_data']['name'] = '月度运势开通';
                } else if ($orders_details['order_type'] == 4)
                {
                    $info['goods_data']['name'] = '年度运势开通';
                } else
                {
                    $info['goods_data']['name'] = '运势开通';
                }
                //获取商品信息
                $info['goods_data']['price'] = current($detail['goods_data'])['now_prize'];
                $info['goods_data']['des'] = '';
                //获取档案信息
                $recode = current($detail['recode_data']);
                $info['recode_data']['des'] = count($detail['recode_data']) > 1 ? '全部档案' : $recode['name'];
                $info['recode_data']['rids'] = implode(',', array_column($detail['recode_data'], 'id'));
                $info['order_data'][] = [
                    'name' => '开通日期',
                    'value' => $detail['fortune_data']['start_time'] . '至' . $detail['fortune_data']['end_time'],
                ];
                $orders_details['rid'] = current($detail['recode_data'])['id'];
                $orders_details['time'] = $detail['fortune_data']['start_time'];
                break;
            case (int)$orders_details['order_type'] === 5://地图
                $detail = $ordersModel->MapRead($orders_details);
                $info['goods_data']['name'] = '幸运之城解锁';
                //获取订单商品价格
                $info['goods_data']['price'] = array_sum(array_map(static function ($val)
                {
                    return $val['now_prize'];
                }, $detail['goods_data']));
                //获取订单商品名称
                $info['goods_data']['des'] = implode(',', array_map(static function ($val)
                {
                    if ($val['id'] == 19)
                    {
                        return '幸运之城全内容打包解锁';
                    }

                    return $val['name'];
                }, $detail['goods_data']));
                //获取档案信息
                $recode = current($detail['recode_data']);
                $info['recode_data']['des'] = $recode['name'];
                $info['recode_data']['rids'] = $recode['id'];
                $orders_details['rid'] = current($detail['recode_data'])['id'];
                break;
            case (int)$orders_details['order_type'] === 6 ://教学视频
                $detail = $ordersModel->VideoRead($orders_details);
                $goods = current($detail['goods_data']);
                //获取商品信息
                $info['goods_data']['name'] = '一生报告解锁';
                $info['goods_data']['price'] = $goods['now_prize'];
                $info['goods_data']['des'] = $detail['goods_data_des'];
                break;
            case (int)$orders_details['order_type'] === 7://本命预测
                $detail = $ordersModel->MapRead($orders_details);
                $goods = current($detail['goods_data']);
                //获取商品信息
                $info['goods_data']['name'] = '一生报告解锁';
                $info['goods_data']['price'] = $goods['now_prize'];
                $info['goods_data']['des'] = $detail['data']['des'];
                //获取档案信息
                $recode = current($detail['recode_data']);
                $info['recode_data']['des'] = $recode['name'];
                $info['recode_data']['rids'] = $recode['id'];
                $orders_details['rid'] = current($detail['recode_data'])['id'];
                break;
            case (int)$orders_details['order_type'] === 8://会员
                $detail = $ordersModel->VipRead($orders_details);
                $goods = current($detail['goods_data']);
                //获取商品信息
                $info['goods_data']['name'] = '开通会员';
                $info['goods_data']['price'] = $goods['now_prize'];
                $info['goods_data']['des'] = $goods['name'];
                //若会员支付成功，则显示有效期
                if ((int)$orders_details['status'] === 4)
                {
                    $info['order_data'][] = [
                        'name' => '开通日期',
                        'value' => $detail['vip_start_time'] . '至' . $detail['vip_end_time'],
                    ];
                }
                break;
            case (int)$orders_details['order_type'] === 15://定制报告
                $customReport = $ordersModel->CustomReport($orders_details);
                $orders_details['qid'] = $customReport['question_data']['id'];
                $orders_details['qstatus'] = $customReport['question_data']['status'];
                $info['goods_data']['name'] = '定制报告';
                $info['goods_data']['price'] = $customReport['goods_data']['price'];
                $info['goods_data']['des'] = '';
                if ($customReport['question_data']['is_merge'])
                {
                    $info['recode_data']['des'] = '全部档案';
                } else
                {
                    $info['recode_data']['des'] = current($customReport['recode_data'])['name'];
                }
                $info['recode_data']['rids'] = implode(',', array_column($customReport['recode_data'], 'id'));
                $completeAnswerTime = $this->completeAnswerTime / 3600;
                if ($orders_details['status'] == 1 && $customReport['question_data']['status_link']['type'] == 2)
                {
                    // $info['note_tips'] = $customReport['question_data']['status_link']['order_des'];
                    //                    $info['note_tips'] = "注：8:00-16:00的提问，将在接单后6小时内得到回复，16:00-次日8:00的提问，将在次日8:00开始计时，{$completeAnswerTime}小时内得到回复";
                    $info['note_tips'] = '';
                }
                if ((int)$orders_details['status'] === 1)
                {
                    $info['des'] = "占星师接单后，{$completeAnswerTime}小时内得到回复";
                }
                break;
            case (int)$orders_details['order_type'] === 16://塔罗
                $tarot = $ordersModel->tarot($orders_details);
                $orders_details['qid'] = $tarot['history']['id'];
                $info['goods_data']['name'] = '塔罗占卜';
                $info['goods_data']['price'] = current($tarot['goods_data'])['now_prize'];
                $info['goods_data']['des'] = $tarot['history']['content'];
                break;
            case (int)$orders_details['order_type'] === 17://合盘报告
                $synastryReport = $ordersModel->SynastryReport($orders_details);
                $goods = current($synastryReport['goods_data']);
                $extend = \GuzzleHttp\json_decode($orders['extend'], true);
                $startTime = $extend['synastry_report']['start_time'] ?? NULL;
                if ($startTime)
                {
                    $addYear = $synastryReport['goods_data'][$goods['id']]['expire_time'];
                    $info['order_data'][] = [
                        'name' => '开通时间',
                        'value' => date('Y.m', $startTime) . '至' . date('Y.m', strtotime($addYear . ' -1month', $startTime)),
                    ];
                }
                $info['goods_data']['srid'] = $extend['synastry_report']['srid'] ?? 1;
                $info['goods_data']['name'] = config('synastryreport')[$info['goods_data']['srid']]['good_name'] ?? $goods['name'];
                $info['goods_data']['price'] = $goods['now_prize'];
                $info['goods_data']['des'] = '当前关系：' . $synastryReport['relation_data']['name'];
                $info['recode_data']['des'] = implode('&', array_column($synastryReport['recode_data'], 'name'));
                $info['recode_data']['rids'] = implode(',', array_column($synastryReport['recode_data'], 'id'));
                break;
            case (int)$orders_details['order_type'] === 18://心理测试
                $detail = $ordersModel->MentalTestDetail($orders_details);
                //获取商品信息
                $info['goods_data']['name'] = $detail['name'];
                $info['goods_data']['des'] = $detail['short_describe'];
                $info['goods_data']['img'] = $detail['intro_picture'];
                $info['goods_data']['price'] = $detail['price_original'];

                $orders_details['is_skip'] = 1;
                break;
        }
        if ($orders_details['is_skip'])
        {
            $orders_details['goods_data'] = $detail['goods_data'] ?? [];
            $linkInfo = $ordersModel->orderTypeLink($orders_details);
            $info['target'] = $linkInfo['target'];
            $info['link'] = $linkInfo['link'];
        } else
        {
            $info['target'] = 'local';
            $info['link'] = 'empty';
        }

        return $info;
    }

    /**
     * 获取订单详情按钮和图标
     * @param $orders
     * @return mixed
     */
    private function getReadOrderBtn($orders)
    {
        $bans = config('zhunleorder');
        $data['icon'] = $bans['order_icon'][$orders['status']];
        $data['btn'] = $bans['read_order_btn'][$orders['status']];
        if (in_array((int)$orders['status'], [3, 4], true) && in_array((int)$orders['order_type'], [1, 5, 6], true))
        {
            $data['btn'] = [];
        }

        if (18 === (int)$orders['order_type'])
        {//如果为心理测评，那么什么按钮都不显示
            $data['btn'] = [];
        }

        return $data;
    }

    /**
     * 检测用户是否绑定手机号
     * @return bool
     */
    private function CheckUserTel()
    {
        // TODO 暂时关闭下单验证手机号逻辑
        //        if (!$this->user['tel'])
        //        {
        //            throw new ApiException('请绑定手机号后进行购买', 200, 407);
        //        }
        return true;
    }

    /**
     * 接口，下单
     * order_type 1=>校准生辰,2=>日运,3=>月运,4=>年运,5=>幸运之城,6=>教学视频,7=>本命预测,8=>vip会员
     * order_id 01=>校准生辰 02=>运势 03=>幸运之城，04=>教学视频，05=>本命预测
     * @return Json
     * @throws Exception
     */
    public function pay_unlock()
    {
        $this->msg = '';
        $this->CheckUserTel();
        $param['trade_type'] = input('param.trade_type/d', 0);
        $param['order_type'] = input('param.order_type/d', 0);
        $param['gids'] = input('param.gids/s', '');
        $param['param'] = input('param.param', '');
        $param['openid'] = input('param.openid/s', '');
        $param = OrdersLib::pay_order_param_format($this->user['id'], $param);
        if ($param['price'] >= 0.01)
        {
            //生成订单数据并下单
            $arr = $this->SaveOrder($param);

            return show(config('code.success'), '下单成功', $arr['data']);
        }

        return show(config('code.error'), '下单金额有误');
    }

    /**
     * 生成订单，并下单
     * @param $param ['order_type','trade_type','rid','cid','reid','gids','goods_info','price'，'start_time','out_trade_no','account','extend','pay_des','openid']
     * @return array|bool|Json
     * @throws Exception
     */
    private function SaveOrder($param)
    {
        $CouponModel = new UserCoupon();
        $orderModel = new OrdersCacheModel();
        $gid = current($param['gids']);
        Db::startTrans();
        try
        {
            //若是运势，则添加运势中间表数据
            if (in_array($param['order_type'], [2, 3, 4], false))
            {
                $middle_res = $this->pay_fortune($param['rid'], $param['start_time'], $param['order_type']);
                if ($middle_res === false)
                {
                    throw new ApiException('下单失败,请重新操作');
                }
            }
            //生成订单数据
            $insert = [
                'order_type' => $param['order_type'],
                'uid' => $this->user['id'],
                'gid' => current($param['gids']),
                'order_id' => $param['out_trade_no'],
                'reid' => $param['reid'],
                'fid' => $middle_res ?? 0,
                'trade_type' => $param['trade_type'],
                'total_amount' => $param['price'],
                'create_time' => $this->request->time(),
                'status' => 0,
                'account' => $param['account'],
                'extend' => $param['extend'],
            ];
            // 生成订单到数据库
            $oid = $orderModel->SaveData($insert);
            if ($oid === false)
            {
                throw new ApiException('下单失败,请重新操作');
            }
            //添加中间表数据
            if ($param['rid'])
            {
                $middle_res = $this->insertMiddle($param['rid'], $param['gids'], $oid);
                if ($middle_res === false)
                {
                    throw new ApiException('下单失败,请重新操作');
                }
            }
            //添加定制报告问题记录
            if ($param['order_type'] == 15)
            {
                $questionModel = new ZlcrCustomReportQuestion();
                $questionModel->addCustomReport($insert, $param);
            }
            //塔罗记录更新订单编号数据
            if ($param['order_type'] == 16)
            {
                (new ZlTarotRecords())->updateData($param['history_id'], ['order_num' => $param['out_trade_no']]);
            }
            //修改优惠券状态为已锁定
            if ($param['cid'])
            {
                $res = $CouponModel->use_return($this->user['id'], $param['cid'], [
                    'status' => 4,
                    'oid' => $oid,
                    'update_time' => $this->request->time(),
                ]);
                if ($res === false)
                {
                    throw new ApiException($CouponModel->getError());
                }
            }
            //检测订单关闭入队
            PushQueue::CloseOrder($param['out_trade_no']);

            //更新订单详情缓存
            $orderModel->UpdateCache($param['out_trade_no'], 0);
            Db::commit();
        }
        catch (Exception $e)
        {
            Db::rollback();
            Log::write('入库失败信息：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            throw new ApiException('下单失败,请重新操作');
        }

        //支付订单
        $arr = OrdersLib::unifyPayOrder([
            'oid' => $oid,
            'trade_type' => $param['trade_type'],
            'total_amount' => $param['price'],
            'pay_des' => $param['pay_des'],
            'order_id' => $param['out_trade_no'],
            'openid' => $param['openid'],
            'callback_url' => '',
            'order_type' => $param['order_type'],
        ], 1);
        if ($this->headers['app-type'] === 'ios')
        {
            $new_gid = [];
            foreach ($param['gids'] as $gid)
            {
                $new_gid[] = 'apple_pay_' . $gid;
            }
            $skuId = implode(',', $new_gid);
            $arr['data']['skuId'] = $skuId;
        }

        return $arr;
    }

    /**
     * 运势下单
     * @param int $rid
     * @param int $start_time
     * @param int $order_type
     * @return bool|int|string
     */
    private function pay_fortune($rid, $start_time, $order_type)
    {
        $arr = [
            'type' => $order_type - 1,
            'rids' => $rid,
            'time' => $start_time,
            'create_time' => $this->request->time(),
        ];

        return (new Fortune())->insertGetId($arr); //每日运势id
    }

    /**
     * 添加中间表数据
     * @param $rid
     * @param $gids
     * @param $oid
     * @return bool
     */
    private function insertMiddle($rid, $gids, $oid)
    {
        $array = [];
        foreach ($gids as $k => $v)
        {
            $array[] = [
                'gid' => $v,
                'oid' => $oid,
                'rid' => $rid,
            ];
        }
        //中间表
        (new OrdersGoods())->insertAll($array);
    }
}
